package camelinaction.Interceptor;

import camelinaction.BufferFactory;
import camelinaction.LoginRequest;
import camelinaction.PrivateChatRequest;
import camelinaction.PublicChatRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.PooledByteBufAllocator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.ByteOrder;
import java.nio.charset.Charset;

@Component
@Slf4j
public class ContentCodeInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        /*REGISTER_AND_LOGIN((short) 1, (short) 1, "PLAYER","REGISTER_AND_LOGIN","/chatonline/", "registerAndLogin"),
                LOGIN((short)1, (short)2,"PLAYER", "LOGIN","/chatonline/","login"),
                PUBLIC_CHAT((short)2, (short)1,"CHAT", "PUBLIC_CHAT","/chatonline/","publicChat"),
                PRIVATE_CHAT((short)2, (short)2,"CHAT","PRIVATE_CHAT", "/chatonline/","privateChat"),
                PUSHCHAT((short)2, (short)101,"CHAT", "PUSHCHAT","/chatonline/","pushChat");*/

        byte[] content= ((MockHttpServletRequest)httpServletRequest).getContentAsByteArray();
        //编码格式的调整
        if(httpServletRequest.getRequestURI().equalsIgnoreCase("/chatonline/registerAndLogin")
                ||httpServletRequest.getRequestURI().equalsIgnoreCase("/chatonline/login")){


            LoginRequest loginRequest=parseContent(content);
            ObjectMapper objectMapper = new ObjectMapper();
            //objectToJson = objectMapper.writeValueAsString(loginRequest);
            ((MockHttpServletRequest) httpServletRequest).setContent(objectMapper.writeValueAsBytes(loginRequest));
        }

        if(httpServletRequest.getRequestURI().equalsIgnoreCase("/chatonline/publicChat")){
            PublicChatRequest publicChatRequest=null;
            publicChatRequest=parsepbulicContent(content);
            ObjectMapper objectMapper = new ObjectMapper();
            //objectToJson = objectMapper.writeValueAsString(loginRequest);
            ((MockHttpServletRequest) httpServletRequest).setContent(objectMapper.writeValueAsBytes(publicChatRequest));
        }
        if(httpServletRequest.getRequestURI().equalsIgnoreCase("/chatonline/privateChat")){
            PrivateChatRequest privateChatRequest=null;
            privateChatRequest=parseprivatechateContent(content);
            ObjectMapper objectMapper = new ObjectMapper();
            ((MockHttpServletRequest) httpServletRequest).setContent(objectMapper.writeValueAsBytes(privateChatRequest));
        }
        if(httpServletRequest.getRequestURI().equalsIgnoreCase("/chatonline/pushChat")){

        }


        System.out.println("prehandle方法执行了");
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle方法执行了");
       /* String result="";
        if(httpServletRequest.getRequestURI().equalsIgnoreCase("/chatonline/registerAndLogin")
                ||httpServletRequest.getRequestURI().equalsIgnoreCase("/chatonline/login")){
             result=    ((MockHttpServletResponse)httpServletResponse).getContentAsString();

        }

        //String result = servletResponse.getContentAsString();
        log.info("springmvc返回的结果是:"+result);
        JSONObject jsonObject= (JSONObject) JSONObject.parseObject(result, Result.class).getContent();
        //Result<?> result1=(Result<?>)JSONObject.parse(result);
        log.info("springmvc返回的结果是,result中的内容:"+jsonObject);
        ((MockHttpServletResponse)httpServletResponse).*/
        //Response response=new Response(request);
        //response.setData(jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8));
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("afterCompletion方法执行了");
    }
    private PrivateChatRequest parseprivatechateContent(byte[] data) {
        ByteBufAllocator bufAllocator = PooledByteBufAllocator.DEFAULT;
        ByteOrder BYTE_ORDER = ByteOrder.BIG_ENDIAN;
        //readBuffer = BufferFactory.getBuffer(data);
        ByteBuf buffer = bufAllocator.heapBuffer();
        buffer = BufferFactory.getBuffer(data);
        //buffer = buffer.order(BYTE_ORDER);
        PrivateChatRequest privateChatRequest=new PrivateChatRequest();
        privateChatRequest.setTargetPlayerId(buffer.readLong());
        privateChatRequest.setContext(readString(buffer));
        //privateChatRequest.setContext(readString(buffer));
		/*LoginRequest loginRequest=new LoginRequest();
		loginRequest.setPlayerName(readString(buffer));
		loginRequest.setPassward(readString(buffer));*/
        return privateChatRequest;
    }
    private PublicChatRequest parsepbulicContent(byte[] data) {
        //虽然已经是byte[]，但是还需要转为ByteBuf来进行解码
        ByteBufAllocator bufAllocator = PooledByteBufAllocator.DEFAULT;
        ByteOrder BYTE_ORDER = ByteOrder.BIG_ENDIAN;
        //readBuffer = BufferFactory.getBuffer(data);
        ByteBuf buffer = bufAllocator.heapBuffer();
        buffer = BufferFactory.getBuffer(data);
        //buffer = buffer.order(BYTE_ORDER);
        PublicChatRequest publicChatRequest=new PublicChatRequest();
        publicChatRequest.setContext(readString(buffer));
		/*LoginRequest loginRequest=new LoginRequest();
		loginRequest.setPlayerName(readString(buffer));
		loginRequest.setPassward(readString(buffer));*/
        return publicChatRequest;
    }
    private LoginRequest parseContent(byte[] data) {
        //虽然已经是byte[]，但是还需要转为ByteBuf来进行解码
        ByteBufAllocator bufAllocator = PooledByteBufAllocator.DEFAULT;
        ByteOrder BYTE_ORDER = ByteOrder.BIG_ENDIAN;
        //readBuffer = BufferFactory.getBuffer(data);
        ByteBuf buffer = bufAllocator.heapBuffer();
        buffer = BufferFactory.getBuffer(data);
        //buffer = buffer.order(BYTE_ORDER);
        LoginRequest loginRequest=new LoginRequest();
        loginRequest.setPlayerName(readString(buffer));
        loginRequest.setPassward(readString(buffer));
        return loginRequest;
    }
    public String readString(ByteBuf readBuffer) {
        int size = readBuffer.readShort();
        if (size <= 0) {
            return "";
        }

        byte[] bytes = new byte[size];
        readBuffer.readBytes(bytes);

        return new String(bytes, Charset.forName("UTF-8"));
    }
}
